use axum::{
    extract::{Path, State},
    http::{HeaderMap, Method, StatusCode, Uri},
    response::Response,
    Json,
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{info, warn};

// 路由规则定义
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteRule {
    pub id: String,
    pub name: String,
    pub pattern: String, // 路由匹配模式，支持通配符
    pub target_url: String,
    pub methods: Vec<String>, // 允许的HTTP方法
    pub enabled: bool,
    pub rate_limit: Option<u32>, // 每秒请求限制
    pub timeout: u64, // 超时时间（秒）
}

// 路由统计信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RouteStats {
    pub total_requests: u64,
    pub success_requests: u64,
    pub failed_requests: u64,
    pub average_response_time: f64,
}

// 消息路由服务
pub struct MessageRouter {
    routes: Arc<RwLock<HashMap<String, RouteRule>>>,
    stats: Arc<RwLock<HashMap<String, RouteStats>>>,
}

impl MessageRouter {
    pub fn new() -> Self {
        Self {
            routes: Arc::new(RwLock::new(HashMap::new())),
            stats: Arc::new(RwLock::new(HashMap::new())),
        }
    }

    // 添加路由规则
    pub async fn add_route(&self, rule: RouteRule) -> Result<(), String> {
        let mut routes = self.routes.write().await;
        if routes.contains_key(&rule.id) {
            return Err(format!("Route with id {} already exists", rule.id));
        }
        routes.insert(rule.id.clone(), rule);
        Ok(())
    }

    // 删除路由规则
    pub async fn remove_route(&self, route_id: &str) -> Result<(), String> {
        let mut routes = self.routes.write().await;
        if routes.remove(route_id).is_none() {
            return Err(format!("Route with id {} not found", route_id));
        }
        
        let mut stats = self.stats.write().await;
        stats.remove(route_id);
        Ok(())
    }

    // 获取路由规则
    pub async fn get_route(&self, route_id: &str) -> Option<RouteRule> {
        let routes = self.routes.read().await;
        routes.get(route_id).cloned()
    }

    // 获取所有路由规则
    pub async fn get_all_routes(&self) -> Vec<RouteRule> {
        let routes = self.routes.read().await;
        routes.values().cloned().collect()
    }

    // 匹配路由
    pub async fn match_route(&self, path: &str, method: &str) -> Option<RouteRule> {
        let routes = self.routes.read().await;
        
        for rule in routes.values() {
            if !rule.enabled {
                continue;
            }
            
            // 检查方法匹配
            if !rule.methods.is_empty() && !rule.methods.iter().any(|m| m == method) {
                continue;
            }
            
            // 简单路径匹配（支持通配符）
            if Self::path_matches(&rule.pattern, path) {
                return Some(rule.clone());
            }
        }
        
        None
    }

    // 路径匹配逻辑
    fn path_matches(pattern: &str, path: &str) -> bool {
        if pattern == path {
            return true;
        }
        
        // 支持通配符匹配
        if pattern.ends_with("/*") {
            let base_pattern = &pattern[..pattern.len() - 2];
            return path.starts_with(base_pattern);
        }
        
        false
    }

    // 更新路由统计
    pub async fn update_stats(&self, route_id: &str, success: bool, response_time: f64) {
        let mut stats = self.stats.write().await;
        let route_stats = stats.entry(route_id.to_string()).or_insert(RouteStats {
            total_requests: 0,
            success_requests: 0,
            failed_requests: 0,
            average_response_time: 0.0,
        });
        
        route_stats.total_requests += 1;
        if success {
            route_stats.success_requests += 1;
        } else {
            route_stats.failed_requests += 1;
        }
        
        // 更新平均响应时间（移动平均）
        route_stats.average_response_time = 
            (route_stats.average_response_time * (route_stats.total_requests - 1) as f64 + response_time) 
            / route_stats.total_requests as f64;
    }

    // 获取路由统计
    pub async fn get_stats(&self, route_id: &str) -> Option<RouteStats> {
        let stats = self.stats.read().await;
        stats.get(route_id).cloned()
    }

    // 获取所有路由统计
    pub async fn get_all_stats(&self) -> HashMap<String, RouteStats> {
        let stats = self.stats.read().await;
        stats.clone()
    }
}

// API请求和响应结构
#[derive(Debug, Serialize, Deserialize)]
pub struct CreateRouteRequest {
    pub name: String,
    pub pattern: String,
    pub target_url: String,
    pub methods: Vec<String>,
    pub rate_limit: Option<u32>,
    pub timeout: u64,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct CreateRouteResponse {
    pub route_id: String,
    pub message: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RouteListResponse {
    pub routes: Vec<RouteRule>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct RouteStatsResponse {
    pub stats: HashMap<String, RouteStats>,
}

// API处理函数
pub async fn create_route(
    State(router): State<Arc<MessageRouter>>,
    Json(payload): Json<CreateRouteRequest>,
) -> Result<Json<CreateRouteResponse>, StatusCode> {
    let route_id = format!("route_{}", std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis());
    
    let rule = RouteRule {
        id: route_id.clone(),
        name: payload.name,
        pattern: payload.pattern,
        target_url: payload.target_url,
        methods: payload.methods,
        enabled: true,
        rate_limit: payload.rate_limit,
        timeout: payload.timeout,
    };
    
    router.add_route(rule).await
        .map_err(|e| {
            warn!("Failed to create route: {}", e);
            StatusCode::BAD_REQUEST
        })?;
    
    Ok(Json(CreateRouteResponse {
        route_id,
        message: "路由创建成功".to_string(),
    }))
}

pub async fn list_routes(
    State(router): State<Arc<MessageRouter>>,
) -> Json<RouteListResponse> {
    let routes = router.get_all_routes().await;
    Json(RouteListResponse { routes })
}

pub async fn get_route_stats(
    State(router): State<Arc<MessageRouter>>,
) -> Json<RouteStatsResponse> {
    let stats = router.get_all_stats().await;
    Json(RouteStatsResponse { stats })
}

pub async fn delete_route(
    State(router): State<Arc<MessageRouter>>,
    Path(route_id): Path<String>,
) -> Result<Json<CreateRouteResponse>, StatusCode> {
    router.remove_route(&route_id).await
        .map_err(|e| {
            warn!("Failed to delete route: {}", e);
            StatusCode::NOT_FOUND
        })?;
    
    Ok(Json(CreateRouteResponse {
        route_id,
        message: "路由删除成功".to_string(),
    }))
}